<!-- 创建、编辑消息 -->
<template>
  <div class="add_edit_message">
    <Form ref="form" :model="editorInfo" :rules="rules" :label-width="110">
      <FormItem label="标题：" prop="msgTitle">
        <Row>
          <Col span="15">
            <Input :maxlength="20" v-model="editorInfo.msgTitle" placeholder="请输入标题"></Input>
          </Col>
        </Row>
      </FormItem>
      <FormItem label="发送对象：" required>
        <Row>
          <Col span="1">公司</Col>
          <Col span="14">
            <tree_select
              v-model="editorInfo.sendCompanys"
              ref="areaTree"
              :treeList="companyList"
              selectPlaceholder="请选择"
              :maxTagCount="3"></tree_select>
          </Col>
        </Row>
        <Row class="M_top_10">
          <Col span="1">个人</Col>
          <Col span="14">
            <Select
              v-model="editorInfo.sendPersonals"
              filterable
              @on-query-change="searchUser"
              label-in-value
              multiple
              placeholder="请输入OA工号"
              clearable>
              <Option
                v-for="option in userList"
                :value="option.userId"
                :key="option.userId"
                :label="option.userName + '-' + option.workNo"></Option>
            </Select>
          </Col>
        </Row>
        <p v-show="companyIdsOrUserId" class="editorTip">请选择发送对象</p>
      </FormItem>
      <Row>
        <Col span="24">
          <FormItem label="发送时效：" prop="sendFlag" required>
            <Radio-group v-model="editorInfo.sendFlag">
              <Radio :label="1" :disabled="isdisabled">实时发送</Radio>
              <Radio :label="2" :disabled="isdisabled">定时发送</Radio>
            </Radio-group>
          </FormItem>
        </Col>
      </Row>
      <Row>
        <Col span="24">
          <FormItem label="发送端口：" prop="sendPort" required>
            <CheckboxGroup v-model="editorInfo.sendPort">
              <Checkbox :label="'2'">后台</Checkbox>
              <Checkbox :label="'1'">APP</Checkbox>
            </CheckboxGroup>
          </FormItem>
        </Col>
      </Row>
      <Row v-if="editorInfo.sendPort && editorInfo.sendPort.indexOf('1') > -1">
        <Col span="10" style="display: flex">
          <FormItem label="首页弹框：" prop="popFlag" required>
            <Radio-group v-model="editorInfo.popFlag">
              <Radio :label="1">是</Radio>
              <Radio :label="0">否</Radio>
            </Radio-group>
          </FormItem>
          <p style="line-height: 40px">（仅对APP端口生效）</p>
        </Col>
      </Row>
      <Row v-if="editorInfo.sendFlag == 2">
        <Col span="14">
          <FormItem label="发送时间：" prop="sendTime">
            <DatePicker
              type="datetime"
              format="yyyy-MM-dd HH:mm"
              :start-date="new Date()"
              :options="saveTimeOptions"
              :disabled="isdisabled"
              v-model="editorInfo.sendTime"></DatePicker>
          </FormItem>
        </Col>
      </Row>
      <FormItem label="发送内容：" prop="sendContent" required>
        <dt-editor v-model="editorInfo.sendContent"></dt-editor>
      </FormItem>
      <Row>
        <Col span="8" offset="8">
          <Row type="flex" justify="space-between" class="footer">
            <Button type="primary" @click="addEditReset" style="margin-right: 8px">关闭</Button>
            <Button type="primary" :loading="buttonLoading" @click="addEditSubmit(1)">保存</Button>
            <Button
              v-if="editorInfo.sendFlag != 2"
              type="primary"
              :loading="buttonLoading"
              @click="addEditSubmit(2)"
              style="margin-left: 8px">
              发送
            </Button>
          </Row>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
  import dtEditor from '@/components/dt/editor/index.vue'
  const saveTimeRule = (rule, value, callback) => {
    if (value) {
      if (value.getTime() < new Date().getTime()) {
        callback(new Error('发送时间必须大于当前时间，请修改后重试！'))
      } else {
        callback()
      }
    } else {
      callback(new Error('请选择发送时间'))
    }
  }
  import tree_select from '@/components/tree_select.vue'
  import teamsApi from '@/biz/buildingManagement/teams'
  import msgApi from '@/biz/message'
  import toolApi from '@/biz/base/tool'
  export default {
    components: {
      tree_select,
      dtEditor
    },
    data() {
      return {
        editorInfo: {
          msgTitle: '',
          sendCompanys: [],
          sendFlag: 1,
          sendTime: '',
          sendPersonals: [],
          sendContent: '',
          sendPort: [],
          jumpFlag: 1,
          jumpType: 1,
          popFlag: 1
        },
        companyList: [],
        userList: [],
        rules: {
          msgTitle: { required: true, message: '请填写标题', trigger: 'change' },
          sendTime: { required: true, validator: saveTimeRule, trigger: 'change' },
          sendContent: { required: true, message: '请输入正文', trigger: 'change' },
          sendPort: { required: true, message: '请选择发送端口', trigger: 'change', type: 'array' },
          popFlag: { required: true, message: '请选择首页是否弹框', trigger: 'change', type: 'number' }
        },
        companyIdsOrUserId: false,
        buttonLoading: false,
        isdisabled: false,
        saveTimeOptions: {
          disabledDate(date) {
            return date && date.valueOf() < Date.now() - 86400000
          }
        }
      }
    },
    methods: {
      //根据工号查人员
      searchUser(filterTxt) {
        if (filterTxt.length < 5 || filterTxt.length > 8) {
          return false
        }
        teamsApi
          .getByWorkNo({
            workNo: filterTxt
          })
          .then((res) => {
            this.userList = res
          })
      },
      // 公司
      getOrganizationTree(data) {
        toolApi.organization(2).then((res) => {
          this.companyList = res && res.filter((item) => item.orgId != 320)
          let arr = []
          if (data) {
            this.companyList.forEach((itemC) => {
              itemC.children.forEach((itemL) => {
                data.forEach((itemD) => {
                  if (itemD == itemL.id) {
                    this.$set(itemL, 'checked', true)
                    arr.push(itemL.id)
                  }
                })
              })
            })
            this.editorInfo.sendCompanys = arr
          }
        })
      },
      //保存/发送 type： 1：保存 2：发送
      addEditSubmit(type) {
        console.log(type, this.editorInfo)
        let isAdd = this.$route.query.type
        this.$refs.form.validate((valid) => {
          if (valid) {
            let sendCompanyLen = this.editorInfo.sendCompanys.length,
              sendPersonalLen = this.editorInfo.sendPersonals.length,
              sendCompany = '',
              sendPersonal = '',
              sendPort = ''
            if (sendCompanyLen == 0 && sendPersonalLen == 0) {
              this.companyIdsOrUserId = true
              return false
            } else {
              this.companyIdsOrUserId = false
              sendCompany = this.editorInfo.sendCompanys.join(',')
              sendPersonal = this.editorInfo.sendPersonals.join(',')
              sendPort = this.editorInfo.sendPort.join(',')
            }
            let params = {
              ...this.editorInfo,
              sendCompany,
              sendPersonal,
              sendPort
            }
            params.updateId = this.$dt.userInfo().userId
            console.log(params, 'formValidateAdd')
            if (type == 1) {
              params.saveState = 1 //发送状态 1.保存
            } else {
              params.saveState = 2 //发送状态 2.已发送
            }
            if (isAdd == 'add') {
              params.createId = this.$dt.userInfo().userId
              msgApi.msgInsert(params).then((res) => {
                this.$dt.notify.emit('messageReadChange')
                this.$router.replace({
                  path: 'messageLog'
                })
              })
            } else if (isAdd == 'edit') {
              params.msgId = this.$route.query.msgId
              msgApi.updateMsg(params).then((res) => {
                this.$router.replace({
                  path: 'messageLog'
                })
              })
            }
          }
        })
      },
      //关闭
      addEditReset() {
        let that = this
        this.$Modal.confirm({
          title: '退出',
          content: `数据还未保存，是否确认关闭页面？`,
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            that.$router.replace({
              path: 'messageLog'
            })
          }
        })
      },
      //编辑时获取消息详情
      getMsgDetail(msgId) {
        let params = {
          msgId
        }
        msgApi.getMessageDetails(params).then((res) => {
          res.userRespList.forEach((item) => {
            item.userId = String(item.userId)
          })
          this.editorInfo.sendContent = res.sendContent
          this.editorInfo.msgTitle = res.msgTitle
          this.editorInfo.sendFlag = res.sendFlag
          this.editorInfo.sendTime = res.sendTime
          this.editorInfo.popFlag = res.popFlag
          this.userList = res.userRespList
          ;(this.editorInfo.sendPersonals = res.sendPersonal ? res.sendPersonal.split(',') : []),
            (this.editorInfo.sendPort = res.sendPort ? res.sendPort.split(',') : []),
            this.getOrganizationTree(res.orgIds)
        })
      }
    },
    mounted() {
      if (this.$route.query && this.$route.query.type == 'edit') {
        this.getMsgDetail(this.$route.query.msgId)
      } else {
        this.getOrganizationTree()
      }
    }
  }
</script>
<style lang="scss" scoped>
  .add_edit_message {
    padding: 20px;

    .M_top_10 {
      margin-top: 10px;
    }

    .editorTip {
      color: #ed4014;
      font-size: 14px;
      position: absolute;
      left: 0;
      bottom: -26px;
    }

    .footer {
      margin-top: 40px;

      .ivu-btn {
        flex: 1;
        text-align: center;
        line-height: 32px;
      }
    }
  }
</style>
